package activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.evaluity.R;

import views.DegreeAdapter;
import views.UniversityAdapter;

import data.DATA_Helper;

import logic.Degree;
import logic.Question;
import logic.Test;
import logic.University;
import logic.User;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainMenu extends Activity {
	
	private DATA_Helper dataHelper = new DATA_Helper(this);
	private HashMap<Integer, Degree> degreeMap = new HashMap<Integer, Degree>();
	
	private Activity activity;
	
	private User usuari;
	private String mailuser;
	
	Context context;
	
//	private class DTO implements Serializable {
//		/**
//		 * 
//		 */
//		private static final long serialVersionUID = 836196007216090164L;
//		private Object content;
//		
//		public DTO(Object content) {
//			this.content = content;
//		}
//		
//		public Object getContent() {
//			return content;
//		}
//	}

	private class StartTestsOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.recentButton:
				ArrayList<Test> recents = (ArrayList<Test>) dataHelper.getRecentTestsIds();
				startTestListsActivity(false, recents);
				break;
			case R.id.offlineButton:
				dataHelper.getOfflineTests();
				startTestListsActivity(true, null);
				break;

			default:
				break;
			}
		}
	}

	private class StartQuestionsOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			List<Question> questions = new ArrayList<Question>();
			switch (v.getId()) {
//			case R.id.mistakenButton:
//				questions = dataHelper.getMistakenQuestions();
//				break;

			default:
				break;
			}
			startQuestionsListsActivity(questions);
		}
	}
	
	private class StartDegreesOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.addDegreeButton:
				startDegreeGeolocationActivity();
				break;

			default:
				break;
			}
		}
	}
	
	private void startDegreeGeolocationActivity() {
		Intent i = new Intent(this, Geolog.class);
		startActivity(i);
	}
	
	private void startTestListsActivity(boolean offline, ArrayList<Test> recents) {
		Intent i = new Intent(this, TestsList.class);
		i.putExtra("offline", offline);
		
		if(recents != null)
			i.putExtra(TestsList.EXTRA_RECENT_TESTS, recents);
		startActivity(i);
	}
	
	private void startQuestionsListsActivity(List<Question> questions) {
		Intent i = new Intent(this, QuestionsList.class);
		startActivity(i);
	}
	
	public void startMainActivity() {
		
		Intent i = new Intent(this, MainMenu.class);
		//i.putExtra(Constants.EXTRA_ACTIVITY, Constants.ASSISTENTS_ACTIVITY);
		startActivity(i);
	}
	
	public void startLoginActivity() {
		
		Intent i = new Intent(this, Login.class);
		//i.putExtra(Constants.EXTRA_ACTIVITY, Constants.ASSISTENTS_ACTIVITY);
		startActivity(i);
	}
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.context = this;
		if (android.os.Build.VERSION.SDK_INT > 9) {
		      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		      StrictMode.setThreadPolicy(policy);
	    }
		
		final User usuario = new User();
	      if(usuario.isUserLoggedIn(this)){
	         usuario.readUser(this);
	         usuari = usuario;
	         mailuser = usuario.getEmail();
	      	//System.out.println(usuario.getEmail());
	      } else 
	    	   startLoginActivity();
	      
	      activity = this;
	      
		setContentView(R.layout.activity_main);
		
//		University u = new University("UniversitatPolitecnicaCatalunya", "UPC", "Catalunya");
//		DATA_Helper.insertUniversity(u);
		
		List<Degree> degrees = DATA_Helper.getDegrees();
		List<String> degNames = new ArrayList<String>();
		
		for (int i = 0; i < degrees.size(); i++) {
			degreeMap.put(i, degrees.get(i));
			degNames.add(degrees.get(i).getName());
		}
		
		if (degrees.size() > 0) {
			//ArrayAdapter<String> degreeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, degNames);
			ListView lv = (ListView) findViewById(R.id.degreeList);
			//lv.setAdapter(degreeAdapter);
			lv.setAdapter(new DegreeAdapter(this, degrees));
			
			lv.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Degree deg = degreeMap.get(position);
					Intent i = new Intent(context, CourseList.class);
					i.putExtra(CourseList.EXTRA_DEGREE_ID, deg.getId());
					startActivity(i);
				}
			});
			
			registerForContextMenu(lv);
		}
		
		StartDegreesOnClickListener degreeListener = new StartDegreesOnClickListener();
		
		Button addDegreeB = (Button) findViewById(R.id.addDegreeButton);
		addDegreeB.setOnClickListener(degreeListener);
		
		StartTestsOnClickListener testsListener = new StartTestsOnClickListener();
		
		Button recentB = (Button) findViewById(R.id.recentButton);
		recentB.setOnClickListener(testsListener);
		
		Button offlineB = (Button) findViewById(R.id.offlineButton);
		offlineB.setOnClickListener(testsListener);
		
//		StartQuestionsOnClickListener questionsListener = new StartQuestionsOnClickListener();
//		Button mistakenB = (Button) findViewById(R.id.mistakenButton);
//		mistakenB.setOnClickListener(questionsListener);
		
		/*Button assistButton4 = (Button) findViewById(R.id.action_logout);
        assistButton4.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				usuario.logout(activity);
				startMainActivity();
			}
		});*/
        
        //TextView text = (TextView) findViewById(R.id.textview);
        //text.setText("Loged in as: "+usuario.getEmail());
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();

		menu.add(0, v.getId(), 0, "Yes, remove");
		// info.position is the position in the ListView

		inflater.inflate(R.menu.context_menu, menu);
		menu.setHeaderTitle("Remove this degree?");

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		Degree selectedDegree = degreeMap.get(info.position);

		if (DATA_Helper.deleteDegreFromDB(selectedDegree)) {
			Toast.makeText(this, "Degree removed successfully", Toast.LENGTH_SHORT).show();
		}
		
		else {
			Toast.makeText(this, "The degree couldn't be removed", Toast.LENGTH_LONG).show();
		}
		
		onCreate(null);
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		
		menu.add(Menu.NONE, R.id.action_logout, Menu.NONE , "Logout ("+mailuser+")");
		
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    	
	            
	        case R.id.action_logout:
			
	        	usuari.logout(activity);
				startMainActivity();
				
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

}
